package com.moter.demo01.requirements;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class NIOClient {
    private final String PATH="src\\main\\java\\com\\moter\\demo01\\requirements\\client.txt";
    private SocketChannel client = null;
    public void initClient(){
        try {
            client = SocketChannel.open();
            client.connect(new InetSocketAddress("192.168.123.183",9090));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
    public void start(){
        initClient();
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);
        write(byteBuffer);
        if(client.isOpen()){//如果服务端通道保持开启
            read(byteBuffer);
        }
    }
    //读数据
    private void read(ByteBuffer byteBuffer) {
        try {
            while (true){
                byteBuffer.clear();
                int read = client.read(byteBuffer);
                if(read>0){
                    byteBuffer.flip();
                    byte[] data = new byte[byteBuffer.limit()];
                    byteBuffer.get(data);
                    System.out.print(new String(data));
                }
                else if(read==0){
                    break;
                }else {
                    System.out.println("服务器中断连接。。。。。");
                    client.close();
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void write(ByteBuffer byteBuffer){
        int read;
        try(FileChannel fileChannel = new FileInputStream(new File(PATH)).getChannel()) {
            while (true){
                byteBuffer.clear();
                read = fileChannel.read(byteBuffer);
                if(read>0){
                    byteBuffer.flip();
                    client.write(byteBuffer);
                }else {
                    break;
                }
            }
            byteBuffer.clear();
        } catch (IOException e) {
            System.out.println("发送数据中断！。。。。。。。");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        NIOClient nioClient = new NIOClient();
        nioClient.start();
    }

}
